from abc import ABC, abstractmethod
from typing import Any, Dict

from services.auddit_service import JObAuditService


class BaseMessageAuditor(ABC):
    """消息审核器抽象基类"""

    @abstractmethod
    def audit(self, payload: Dict[str, Any]) -> Dict[str, Any]:
        """
        执行审核逻辑
        :param payload: 审核所需参数
        :return: 审核结果字典
        """


class JobMessageAuditor(BaseMessageAuditor):
    """职位消息审核器"""

    REQUIRED_FIELDS = {"job_id", "company_id", "job_title"}

    def audit(self, payload: Dict[str, Any]) -> Dict[str, Any]:
        missing_fields = self.REQUIRED_FIELDS - payload.keys()
        if missing_fields:
            raise ValueError(f"职位审核缺少必要字段: {', '.join(missing_fields)}")

        job_id = payload["job_id"]
        company_id = payload["company_id"]
        job_title = payload["job_title"]
        job_description = payload.get("job_description", "")
        audit_ip = payload.get("audit_ip")

        return JObAuditService.audit_job_content(
            job_id=job_id,
            company_id=company_id,
            job_title=job_title,
            job_description=job_description,
            audit_ip=audit_ip,
        )


class PlainTextAuditor(BaseMessageAuditor):
    """通用文本审核器"""

    REQUIRED_FIELDS = {"content"}

    def audit(self, payload: Dict[str, Any]) -> Dict[str, Any]:
        missing_fields = self.REQUIRED_FIELDS - payload.keys()
        if missing_fields:
            raise ValueError(f"文本审核缺少必要字段: {', '.join(missing_fields)}")

        content = payload["content"]
        return JObAuditService.audit_plain_text(content)


class MessageAuditFactory:
    """消息审核工厂"""

    JOB = "job"
    RESUME = "resume"
    TEXT = "text"

    _AUDITOR_REGISTRY = {
        JOB: JobMessageAuditor(),
        RESUME: PlainTextAuditor(),  # 简历抽取后仍走文本审核
        TEXT: PlainTextAuditor(),
    }

    @classmethod
    def get_auditor(cls, audit_type: str) -> BaseMessageAuditor:
        try:
            return cls._AUDITOR_REGISTRY[audit_type]
        except KeyError as exc:
            raise ValueError(f"不支持的审核类型: {audit_type}") from exc


